package com.srwl.mytx.fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.core.content.ContextCompat;

import com.srwl.mytx.Constant;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.domain.CoinTransfer;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.service.TransferService;
import com.srwl.mytx.utils.ClickUtil;
import com.srwl.mytx.utils.GlideLoadUtils;
import com.srwl.mytx.utils.PayUtils;
import com.srwl.mytx.R;
import com.srwl.redpacketui.ui.fragment.SendPacketBaseFragment;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class TransferFragment extends SendPacketBaseFragment {
    private static final String TAG = "TransferFragment";
    private EditText mEtMoneyAmount;

    private Button mBtnPutMoney;
    private String mMoneyAmount;
    private ImageView iv_transferIcon;
    private TextView tv_transferName;


    public static TransferFragment newInstance(String targetUserId) {
        TransferFragment fragment = new TransferFragment();
        Bundle args = new Bundle();
        args.putString(ARGS_TARGET_USER_ID, targetUserId);
        fragment.setArguments(args);
        return fragment;
    }

    public static TransferFragment newInstance(User targetUser) {
        TransferFragment fragment = new TransferFragment();
        Bundle args = new Bundle();
        args.putParcelable(ARGS_TARGET_USER, targetUser);
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    protected int getContentViewLayoutID() {
        return R.layout.rp_fragment_transfer;
    }

//    @Override
//    protected View getLoadingTargetView(View view) {
//        return view.findViewById(R.id.ll_transfer_target);
//    }


    @Override

    protected void initViewsAndEvents(View view, Bundle savedInstanceState) {
        super.initViewsAndEvents(view, savedInstanceState);

        mBtnPutMoney = view.findViewById(R.id.btn_transfer);
        mBtnPutMoney.setOnClickListener(this);
        iv_transferIcon = view.findViewById(R.id.iv_transfer_icon);
        tv_transferName = view.findViewById(R.id.tv_transfer_name);
        if (targetUser != null) {
            //Glide.with(getActivity()).load(targetUser.getAvatar()).diskCacheStrategy(DiskCacheStrategy.ALL).placeholder(R.drawable.tx_default_avatar).into(iv_transferIcon);
            GlideLoadUtils.glideLoad(getActivity(), targetUser.getAvatar(), iv_transferIcon, R.drawable.tx_default_avatar_1);
            String username = targetUser.getUsername();
            if (username == null) {
                username = targetUser.getNick();
            }
            tv_transferName.setText(username);
        }

        enableButton(false);

        mEtMoneyAmount = view.findViewById(R.id.et_transfer_money);
        mPopupParent = getActivity().findViewById(R.id.transfer_title_bar);

        initPopupWindow();

        mEtMoneyAmount.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    String moneyAmount = mEtMoneyAmount.getText().toString();
                    if (!TextUtils.isEmpty(moneyAmount)) {
                        if (moneyAmount.length() == 1 && moneyAmount.indexOf(".") == 0) {
                            enableButton(false);
                            setAmountRedColor();
                            showPopupWindow(mPopupParent, mTvPopupMsg, getString(R.string.input_money_error));
                        } else {
                            try {
                                double money = Double.valueOf(moneyAmount);
                                if (money == 0) {
                                    enableButton(false);
                                    setAmountRedColor();
                                    showPopupWindow(mPopupParent, mTvPopupMsg, getString(R.string.input_money_error));
                                }
                            } catch (NumberFormatException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }
        });
        mEtMoneyAmount.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                //  updateLimit();
                mEtMoneyAmount.setTextColor(ContextCompat.getColor(getActivity(), R.color.rp_text_black));

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() == 0) {

                    enableButton(false);
                    hidePopupWindow();
                } else if (s.length() == 1 && s.toString().indexOf(".") == 0) {
                    enableButton(false);
                    hidePopupWindow();
                } else {
                    double money;
                    try {
                        money = Double.valueOf(s.toString());
                        int posDot = s.toString().indexOf(".");
                        if (money == 0) {
                            //当用户输入.00时,提示输入金额错误
                            if (posDot >= 0 && s.length() > 2) {
                                String[] st = s.toString().split("\\.");
                                if (st.length == 2 && st[1].equals("00")) {

                                    enableButton(false);
                                    setAmountRedColor();
                                    showPopupWindow(mPopupParent, mTvPopupMsg, getString(R.string.input_money_error));
                                } else {
                                    hidePopupWindow();

                                    enableButton(false);
                                }
                            } else {
                                hidePopupWindow();
                                if (getStartZeroNumber(s.toString()) < 9) {

                                    enableButton(false);
                                }
                            }
                            return;
                        }
                        if (posDot < 0) {//只有在没有小数点的情况下走下面方法
                            if (s.toString().startsWith("0") && money >= 1) {
                                if (getStartZeroNumber(s.toString()) == 9) {
                                    return;
                                }
                            }
                        }
                        if (money < mMinLimit) {
                            enableButton(false);
                            setAmountRedColor();
                            String minLimit = String.format(getString(R.string.input_transfer_money_limited_minimum), getNumberLimit(mMinLimit));
                            showPopupWindow(mPopupParent, mTvPopupMsg, minLimit);
                            return;
                        }
                        if (money > mSingleLimit) {
                            enableButton(false);
                            setAmountRedColor();
                            String limit = String.format(getString(R.string.input_transfer_money_limited_max), getNumberLimit(mSingleLimit));
                            showPopupWindow(mPopupParent, mTvPopupMsg, limit);
                            return;
                        }
                        enableButton(true);

                        hidePopupWindow();
                    } catch (NumberFormatException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                String temp = s.toString();
                int posDot = temp.indexOf(".");
                if (posDot < 0) {
                    if (temp.length() - 1 > 8) {
                        s.delete(9, 10);
                    }
                    return;
                }
                if (temp.length() - posDot - 1 > 2) {
                    s.delete(posDot + 3, posDot + 4);
                }
            }
        });
    }

    private void setAmountRedColor() {
        enableButton(false);
        mEtMoneyAmount.setTextColor(ContextCompat.getColor(getActivity(), R.color.rp_money_red_light));

    }

    private void enableButton(boolean enable) {
        mBtnPutMoney.setEnabled(enable);
    }


    @Override
    public void onClick(View v) {
        super.onClick(v);//必须调用父类方法
        if (v.getId() == R.id.btn_transfer) {
            if (ClickUtil.isFastClick()) return;
            hideSoftKeyboard();
            mMoneyAmount = mEtMoneyAmount.getText().toString().trim();
            if (verifyParams()) return;
            CoinTransfer coinTransfer = new CoinTransfer();
            coinTransfer.setAmount(Double.valueOf(mMoneyAmount));
            if (targetUser != null) {
                coinTransfer.settId(targetUser.getuId());
            } else {
                coinTransfer.settId(targetId);
            }
            coinTransfer.setCreated(new Date());
            preparePay(coinTransfer);

        }
    }

    private boolean verifyParams() {
        if (TextUtils.isEmpty(mMoneyAmount)) {
            showPopupWindow(mPopupParent, mTvPopupMsg, getString(R.string.input_money_amount));
            return true;
        }
        if (Double.valueOf(mMoneyAmount) <= 0) {
            showPopupWindow(mPopupParent, mTvPopupMsg, getString(R.string.input_money_error));
            return true;
        }
        if (Double.valueOf(mMoneyAmount) > mSingleLimit) {
            String limit = String.format(getResources().getString(R.string.input_transfer_money_limited_max), getNumberLimit(mSingleLimit));
            showPopupWindow(mPopupParent, mTvPopupMsg, limit);
            return true;
        }
        return false;
    }


    /**
     * 准备支付
     *
     * @param transfer
     */
    private void preparePay(final CoinTransfer transfer) {

        new PayUtils(transfer.getAmount(), getActivity(), new PayUtils.InteractionListener() {
            @Override
            public void onPrepareComplete(String payPassword) {


                coinTransfer(payPassword, transfer);
            }
        });

    }

    private void coinTransfer(String payPassword, CoinTransfer transfer) {

        showLoading();
        Map<String, Object> body = new HashMap<>();
        if (payPassword != null) {
            body.put("payPassword", payPassword);
        }
        body.put("coinTransfer", transfer);
        RetrofitManager.getInstance().createRequest(TransferService.class)
                .coinTransfer(body)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        hideLoading();
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "转账出错：" + response.message());
                            showToast(getString(R.string.system_busy));
                            return;
                        }

                        if (result.isError()) {
                            Log.e(TAG, "转账出错：" + result.getMsg());

                            switch (result.getStatus()) {
                                case Constant.BALANCE_NOT_ENOUGH:
                                    showToast(getString(R.string.balance_not_enough));
                                    break;
                                case Constant.GET_LOCK_FAIL:
                                case Constant.FUND_COUPON_EOOR:
                                    showToast(getString(R.string.system_busy));
                                    break;
                            }
                            return;
                        }
                        Log.d(TAG, "转账完成");
                        BigDecimal balance = (BigDecimal) result.getData();

                        //保留2位小数，多的小数直接丢弃，不做4舍5入
                        double balance1 = balance.setScale(2, BigDecimal.ROUND_DOWN).doubleValue();
                        //更新本地余额
                        UserProfileManager.getInstance().setUserBalance(balance1);
                        getActivity().setResult(Activity.RESULT_OK, new Intent().putExtra("coinTransfer", transfer));
                        getActivity().finish();

                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        hideLoading();
                        Log.e(TAG, "发红包出错：" + t.getMessage());
                        showToast(getString(R.string.system_busy));
                    }
                });

    }


}
